const express=require('express')
const fs=require('fs')
const db=require('../config/dbconfig')
const sms=require('leancloud-storage')
const router=express.Router()

sms.init({
    appId:'a803ohquVWDVxIP8XO4hfErr-gzGzoHsz',
    appKey:'8pdYqDAFgLpump4IgxD4jY0O',
    serverURLs:'https://a803ohqu.lc-cn-n1-shared.com'
})

router.post('/scTouXiang',function (req,resp) {
    let {imgUrl}=req.body
    let baseUrl=imgUrl.replace(/data:image\/jpg;base64,/,'').replace('/\s/g',"+")

    //将64码转为文件
    let dataBuffer=Buffer.from(baseUrl,'base64')
    //保存 得到的保存路径
    let fileName=new Date().getTime()+"_touxiang.jpg"
    // fs.writeFile(保存路径，文件，保存成功后执行的函数)
    fs.writeFile(`./src/upload/${fileName}`,dataBuffer,function (err,data) {
        let url=`upload/${fileName}`
        db.db('insert into touxiang value (null,?)',[url],function (err,data) {
            if (!err) resp.send({data:url})
        })
        /*new Promise((resolve, reject) => {
            db.db('insert into touxiang value (null,?)',[url],function (err,data) {
                if (!err) resolve(data)
            })
        }).then(data=>{
            db.db('select * from touxiang where u_imgSrc = ?',[url],function (err,data) {
                if (!err) resp.send(data)
            })
        })*/
    })
})

router.post('/sendCode',function (req,resp) {
    let {phone}=req.body
    sms.Cloud.requestSmsCode({
        mobilePhoneNumber: phone,
        name: '兴兴保健',
        op:'验证码',
        ttl: 1,
        sign:'web'
    }).then(res=>{
        resp.send({
            code:200,
            msg:'短信发送成功'
        })
    }).catch(err=>{
        console.log(err)
        resp.send({
            code:400,
            msg:'短信发送失败'
        })
    })
})

module.exports=router